﻿using Casamiel.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Casamiel.API.Infrastructure.Filters
{
    /// <summary>
    /// Validate model state filter.
    /// </summary>
    public class ValidateModelStateFilter: ActionFilterAttribute
    {
		private readonly NLog.ILogger logger = LogManager.GetLogger("ModelStateService");
		/// <summary>
		/// Ons the action executing.
		/// </summary>
		/// <param name="context">Context.</param>
		public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
            {
                return;
            }
			var vaErrors = context.ModelState
				.Keys
				.SelectMany(k => context.ModelState[k].Errors)
				.Select(e => e.ErrorMessage)
				.ToArray();
			var validateionErrors = context.ModelState
            .Where(e => e.Value.Errors.Count > 0).Select(e => new
              {
                  Name = e.Key,
                  Message = e.Value.Errors.First().ErrorMessage
              })
                                              .ToArray();
			var json = new
			{
				code = 9999,
				content = validateionErrors,
                msg =string.Join(',', vaErrors)
            };
			var userAgent = string.IsNullOrEmpty(context.HttpContext.Request.Headers["User-Agent"].ToString()) ? context.HttpContext.Request.Headers["UserAgent"].ToString() : context.HttpContext.Request.Headers["User-Agent"].ToString();
			this.logger.Error($"User-Agent{userAgent},IP:{context.HttpContext.Request.GetUserIp()},ActionName:{context.ActionDescriptor.DisplayName},data:{JsonConvert.SerializeObject(json)}");

			context.Result = new JsonResult(json);
        }
    }
}
